#!/usr/bin/env python

import sys
import os

import matplotlib
matplotlib.use('PDF') # We cannot use Qt4Agg since it interferes with pyqt apps 

import pylab
pylab.ioff()

import mmlf
mmlf.setupConsoleLogging(level="info")
if not mmlf.QtCore:
    mmlf.log.error("The MMLF GUI requires the PyQt4 or the Pyside package. "\
                   " You may use  run_mmlf.py instead, however.")
    sys.exit(0)
from mmlf import QtGui, QtCore, QtWebKit

# Check for further dependencies
try:
    import scikits.ann
except ImportError:
    mmlf.log.warning("You do not have the scikits.ann package. Without this package, "
                "the KNN function approximator and model-based learning are not " 
                "available. "
                "Please install it with 'sudo easy_install scikits.ann' "
                "or visit http://www.scipy.org/scipy/scikits/wiki/AnnWrapper.")

from mmlf.gui.explorer import MMLFExplorer
from mmlf.gui.experimenter import MMLFExperimenter
                
class MMLF_GUI(QtGui.QMainWindow):
    """ The main window of the MMLF GUI.
    
    Contains subtabs for the MMLF Explorer, the MMLF Experimenter and the
    Documentation.
    """    
    
    # A signal for indicating that an exception has occurred  
    exceptionOccurredSignal = \
                QtCore.pyqtSignal(basestring, name='exceptionOccurredSignal')
 
    def __init__(self, parent=None):
        super(MMLF_GUI, self).__init__(parent)
        
        self.resize(1024, 768)
        self.setWindowTitle('Maja Machine Learning Framework')
        
        # Forwarding of exceptions to GUI
        self.exceptionOccurredSignal.connect(self._exceptionOccurred)
        
        self.tabWidget = QtGui.QTabWidget(self)
        self.tabWidget.setTabsClosable(False)
        self.explorerTab = MMLFExplorer(self)
        self.tabWidget.addTab(self.explorerTab, "Explorer")
        self.experimenterTab = MMLFExperimenter(self)
        self.tabWidget.addTab(self.experimenterTab, "Experimenter")
        self.documentationTab = QtWebKit.QWebView(self)
        self.documentationTab.load(QtCore.QUrl(self.getHTMLDocumentationBase()
                                                + "/index.html"))
        self.tabWidget.addTab(self.documentationTab, "Documentation") 
        self.tabWidget.setCurrentWidget(self.explorerTab)     
        self.setCentralWidget(self.tabWidget)
        
        # Implement proper shutdown
        self.connect(self, QtCore.SIGNAL('quit()'), self.closeEvent)
        
    def closeEvent(self, event):
        self.explorerTab.tearDown()
        self.experimenterTab.tearDown()
        
        super(MMLF_GUI, self).closeEvent(event)
      
    def _exceptionOccurred(self, exceptionString):
        ret = QtGui.QMessageBox.warning(self, "Exception", exceptionString)

    def getHTMLDocumentationBase(self):
        """ Return base path of documentation. """
        if sys.platform == "win32":
           return "http://mmlf.sourceforge.net/"
        elif os.path.exists("./doc/_build/html/index.html"): # Relative to current directory
            return "file:///" + os.path.abspath("./doc/_build/html")
        elif sys.platform == 'linux2' and os.path.exists("/usr/share/doc/mmlf/index.html"): # Absolute directory
            return "file:///usr/share/doc/mmlf"
        elif os.path.exists(mmlf.getRWPath() + os.sep + "doc" + os.sep + "index.html"): # In  MMLF RW area directory
            return mmlf.getRWPath() + os.sep + "doc"
        else: # On the web
            return "http://mmlf.sourceforge.net/"
            

if __name__ == '__main__':    
    # Initialize MMLF rw area
    mmlf.initializeRWArea()
      
    #Creating Qt application
    app = QtGui.QApplication(sys.argv)
 
    mmlfGUI = MMLF_GUI()
    mmlfGUI.show()
 
    #Initing application
    sys.exit(app.exec_())
    